// store/modules/chat.js
import httpRequest from '@/api/httpRequest';
import indexedDB from '@/services/indexdDB';

const state = {
  chatsList: [],  // 存储所有聊天会话和记录
  publishedList: [],
  receiveList: [],
  loading: false,  // 加载状态
  memberList: []  //会话成员
};

const mutations = {
  SET_CHATS_LIST (state, chatsList) {
    state.chatsList = chatsList;
  },
  SET_LOADING (state, loading) {
    state.loading = loading;
  },
  // 群聊成员
  SET_MEMBER (state, memberList) {
    state.memberList = memberList;
  },
  // 发送
  SET_PUBLISHED (state, publishedList) {
    state.publishedList = publishedList;
  },
  // 收到
  SET_RECEIVE (state, receiveList) {
    state.receiveList = receiveList;
  },
  // 新增：更新单个聊天会话的记录
  UPDATE_CHAT_SESSION (state, updatedChatSession) {
    const index = state.chatsList.findIndex(chat => chat.chatSessionId === updatedChatSession.chatSessionId);
    if (index !== -1) {
      // 找到并更新会话
      // state.chatsList[index] = { ...state.chatsList[index], ...updatedChatSession };
      state.chatsList.splice(index, 1, { ...state.chatsList[index], ...updatedChatSession });
    }
  }
};

const actions = {
  // 异步获取聊天记录
  async fetchChatMessages ({ commit }, token) {
    try {
      commit('SET_LOADING', true);  // 开始加载

      const response = await httpRequest.post('/chat/session/list', { token });
      const chatsList = response.data;
      console.log(chatsList, "chatsList");

      const chatSessionIds = chatsList.map(item => item.chatSessionId);

      // 拉取每个 chatSessionId 对应的聊天记录
      for (let i = 0; i < chatSessionIds.length; i++) {
        const chatSessionId = chatSessionIds[i];

        try {
          const chatRecords = await httpRequest.post('/chat/record/list', {
            token,
            chatSessionId,
            startId: 0,
            limit: 100,
            direction: "down"
          });

          // 找到对应的会话，将记录数据添加进去
          const chatItem = chatsList.find(c => c.chatSessionId === chatSessionId);
          if (chatItem) {
            chatItem.chatData = chatRecords.data;
          }
        } catch (error) {
          console.log(`获取 chatSessionId ${chatSessionId} 的记录时发生错误:`, error);
        }
      }

      // 更新 Vuex 中的 chatsList
      commit('SET_CHATS_LIST', chatsList);
      commit('SET_LOADING', false);  // 加载结束

    } catch (error) {
      console.log("获取聊天会话列表时发生错误:", error);
      commit('SET_LOADING', false);  // 加载结束
    }
  },

  // 新增：处理 WebSocket 消息
  async handleWebSocketMessage ({ commit, state }, data) {
    try {
      const token = sessionStorage.getItem('token');

      if (data.notifyType === 'ChatSessionRecord') {
        // 过滤出符合 chatSessionIdList 中 chatSessionId 的会话
        const chatSessionIdSet = new Set(data.chatSessionIdList);
        const filteredChatSessions = state.chatsList.filter(chat => chatSessionIdSet.has(chat.chatSessionId));

        // 格式化为所需的数据结构
        const result = filteredChatSessions.map(chat => ({
          token: token, // 假设 token 是从 sessionStorage 中获取
          chatSessionId: chat.chatSessionId,
          chatSessionName: chat.chatSessionName,
          chatSessionNotice: chat.chatSessionNotice,
          chatSessionMaster: chat.chatSessionMaster,
          isTop: chat.isTop
        }));

        // 更新数据
        for (let index = 0; index < result.length; index++) {
          let updateData;
          try {
            // 发送更新请求
            updateData = await httpRequest.post('/chat/session/update', result[index]);
            console.log(updateData, "data");

            // 如果返回的错误码是 500，重新请求
            if (updateData.code === 500) {
              console.log("发生错误，正在重新请求...");
              updateData = await httpRequest.post('/chat/session/update', result[index]);
            }

            // maxRecordId 大于当前聊天信息，调用聊天窗口
            for (let i = 0; i < filteredChatSessions.length; i++) {
              if (filteredChatSessions[i].maxRecordId < updateData.data.maxRecordId) {
                const chatRecords = await httpRequest.post('/chat/record/list', {
                  token: token,
                  chatSessionId: filteredChatSessions[i].chatSessionId,
                  startId: 0,
                  limit: 100,
                  direction: "down"
                });

                const num = updateData.data.maxRecordId - filteredChatSessions[i].maxRecordId;
                const updatedChatSession = {
                  ...updateData.data,
                  chatData: chatRecords.data,
                  num: num
                };

                console.log(state.chatsList, updatedChatSession, chatRecords, "activeChatList");
                console.log(num, "num");

                // 更新 IndexedDB
                await indexedDB.updateItem(updatedChatSession);

                // 更新 Vuex 中的 chatsList
                commit('UPDATE_CHAT_SESSION', updatedChatSession);
              }
            }
          } catch (error) {
            console.log('更新会话时发生错误:', error);
          }
        }
      }
    } catch (error) {
      console.log('处理 WebSocket 消息时出错:', error);
    }
  },
  // 异步获取发送文件
  async publishedMessage ({ commit }, token) {
    try {
      // 
      const response = await httpRequest.post('/chat/record/file/send/list', { token });
      const published = response.data.list;

      // 更新 Vuex 中的 chatsList
      commit('SET_PUBLISHED', published);

    } catch (error) {
      console.log("获取发送文件时发生错误:", error);
    }
  },
  // 异步获取收到文件
  async receiveMessage ({ commit }, token) {
    try {
      const response = await httpRequest.post('/chat/record/file/receive/list', { token });
      const receive = response.data.list;

      // 更新 Vuex 中的 chatsList
      commit('SET_RECEIVE', receive);

    } catch (error) {
      console.log("获取收到文件时发生错误:", error);
    }
  },
  async memberMessage ({ commit }, data) {
    try {
      const response = await httpRequest.post('/chat/session/member/list', data);
      const receive = response.data;
      console.log(receive, "receive");


      commit('SET_MEMBER', receive);


    } catch (error) {
      console.log("获取群聊成员时发生错误:", error);
    }
  },
  // 异步请求更新聊天会话
  async updateChatSession ({ commit }, { token, updatedSessionData }) {
    try {
      // 调用 API 更新聊天会话
      const response = await httpRequest.post('/chat/session/update', {
        token,
        chatSessionId: updatedSessionData.chatSessionId,
        chatSessionName: updatedSessionData.chatSessionName,
        chatSessionNotice: updatedSessionData.chatSessionNotice,
        chatSessionMaster: updatedSessionData.chatSessionMaster,
        isTop: updatedSessionData.isTop
      });

      const data = response.data;  // 假设这里返回的是更新后的数据
      // 使用 find 方法查找 id 为 3 的项
      const chatData = state.chatsList.find(chat => chat.chatSessionId === data.chatSessionId)?.chatData;
      const updatedChatSession = {
        ...data,
        chatData,
      };
      // 更新 Vuex 中的 chatsList
      commit('UPDATE_CHAT_SESSION', updatedChatSession);

      // 返回成功的更新数据
      return data;
    } catch (error) {
      console.error('更新聊天会话失败:', error);
      throw error;  // 可根据需要抛出错误以便外部捕获
    }
  }
};

const getters = {
  chatsList (state) {
    return state.chatsList;
  },
  loading (state) {
    return state.loading;
  },
  publishedList (state) {
    return state.publishedList;
  },
  receiveList (state) {
    return state.receiveList;
  },
  memberList (state) {
    return state.memberList;
  },
};

export default {
  state,
  mutations,
  actions,
  getters
};
